package com.sdwulongshan.register.reset.register.tool;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
 * AES工具类
 * @author ForMat
 * @version JDK_1.8.0_221
 */
public final class AESTool {
	/**
	 * 此方法用于获取字符串的AES密文
	 * @author ForMat
	 * @param data 要处理的字符串
	 * @param password AES加密用到的密码
	 * @return AES值
	 */
	public static byte[] encodeing(String data ,String password) {
		try {           
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(256, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = data.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; 
    } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
    } catch (NoSuchPaddingException e) {
            e.printStackTrace();
    } catch (InvalidKeyException e) {
            e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
    } catch (BadPaddingException e) {
            e.printStackTrace();
    }
    return null;
    
	}
	
	public static byte[] decodeing(byte[] data,String password) {
		try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(256, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");            
            Cipher cipher = Cipher.getInstance("AES");
           cipher.init(Cipher.DECRYPT_MODE, key);
           byte[] result = cipher.doFinal(data);
           return result; 
   } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
   } catch (NoSuchPaddingException e) {
           e.printStackTrace();
   } catch (InvalidKeyException e) {
           e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
           e.printStackTrace();
   } catch (BadPaddingException e) {
           e.printStackTrace();
   }
   return null;
	}
	
	
	
	/**
	 * 私有的构造器
	 */
	private AESTool() {
		//  NOOOP
	}

}
